package com.culturalCenter.dataCenter.controller;

import com.culturalCenter.dataCenter.Utils.ApiResult;
import com.culturalCenter.dataCenter.Utils.ResultCode;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import static com.culturalCenter.dataCenter.Utils.ApiResult.instance;

/**
 * 验证码
 */
@Api(value = "验证码")
@RestController
@RequestMapping("code")
@Slf4j
public class CodeController {

    @Resource
    private DefaultKaptcha defaultKaptcha;

    @ResponseBody
    @RequestMapping(value = "/getVerify", method = RequestMethod.POST)
    public ApiResult getVerify(HttpServletResponse response) throws IOException {
        // 生成文字验证码
        String text = defaultKaptcha.createText();
        // 生成图片验证码
        // io流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        BufferedImage image = defaultKaptcha.createImage(text);
        // 写入流中
        ImageIO.write(image, "png", outputStream);
        byte[] bytes = outputStream.toByteArray();//转换成字节
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 转换成base64串
        String png_base64 = encoder.encodeBuffer(bytes).trim();
        // 删除 \r\n
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");
        return instance(ResultCode.SUCCESS, "data:image/jpg;base64," + png_base64);
    }

}
